// 
//  Copyright © 2009 Jiří Zárevúcky <zarevucky.jiri@gmail.com>
// 
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as
//  published by the Free Software Foundation, either version 3 of the
//  License, or (at your option) any later version.
// 
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Affero General Public License for more details.
// 
//  You should have received a copy of the GNU Affero General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// 


using System;
using Galaxium.Protocol.Xmpp.Library.Xml;

namespace Galaxium.Protocol.Xmpp.Library.Core
{
	public enum IqType {
		Get, Set, Result, Error
	}
	
	public class IqEventArgs: EventArgs
	{
		public Iq Iq { get; private set; }
		public IqEventArgs (Iq iq) { Iq = iq; }
	}
	
	public class Iq: Stanza
	{
		public Iq ()
			:base ("iq")
		{
		}

		public Iq (IqType type)
			:this ()
		{
			Type = type;
		}
		
		public Iq (IqType type, string xmlns)
			:this (type, "query", xmlns)
		{
		}
		
		public Iq (IqType type, string query_name, string xmlns)
			:this (type)
		{
			Query = new Element (query_name, xmlns);
		}
		
		public Iq (Element elm) 
			:base (elm)
		{
			if (Name != "iq")
				throw new ArgumentException ();
		}

		public Iq Response ()
		{
			Iq response = new Iq (IqType.Result);
			response.ID = ID;
			response.To = From;
			return response;
		}

		public new IqType Type {
			get {
				switch (base.Type) {
				case "get":    return IqType.Get;
				case "set":    return IqType.Set;
				case "result": return IqType.Result;
				case "error":  return IqType.Error;
				default:       throw new Exception ("Unknown IQ type.");
				}
			}
			set {
				base.Type = value.ToString ().ToLower ();
			}
		}
		
		public Element Query {
			get {
				var q = FirstChild (null, null);
				return (q == null || q.Name == "error") ? null : q;
			}
			set {
				Clear ();
				AppendChild (value);
			}
		}
		
		public string QueryNamespace {
			get {
				var q = Query;
				return (q == null) ? null : q.Namespace;
			}
		}

	}
}
